<template>
    <form action="">
        <table>
            <tbody>
                <tr>
                    <td>书名</td>
                    <td>
                        <input type="text" v-model="fromdata.bookname">
                    </td>
                </tr>
                <tr>
                    <td>作者</td>
                    <td>
                        <input type="text" v-model="fromdata.author">
                    </td>
                </tr>
                <tr>
                    <td>
                        <input type="button" value="保存" @click="btnsave">
                    </td>
                    <td>
                        <input type="button" value="取消" @click="btncenlce">
                    </td>
                </tr>
            </tbody>
        </table>
    </form>
</template>

<script setup>
import { onMounted ,ref} from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { addItem, getByid ,editItem} from '@/api/bookApi'
let route=useRoute()
let router=useRouter()
let fromdata=ref({
    bookname:'',
    author:''
})
// 生命周期函数--挂载后页面渲染
onMounted(async ()=>{
    let id=route.params.id||0
    let obj=await getByid(id)
    console.log(obj);    
    Object.assign(fromdata.value,obj.data)
})
async function btnsave() {
    let id=route.params.id||0
    let resalut;
    if(id){
        resalut=await editItem(id,fromdata.value)
        router.push('/')
    }
    else{
        resalut=await addItem(fromdata.value)
        console.log(resalut);     
        router.push('/')   
    }    
} 
async function btncenlce(){
    router.push('/')   
}
</script>